from common.database import runSql
from flask import Blueprint, request
from model.suggest import suggest, db as suggestDb
from utils.JsonUtil import to_json_all  # 转json
from model.User import User,db as userDb
from utils.Result import Response  # 统一返回工具类
import datetime
from sqlalchemy import desc
import json

# 蓝图名
suggest_blueprint = Blueprint('suggest', __name__)
# 创建工具类实例
Result = Response()


# 添加建议
@suggest_blueprint.route('/add', methods=['POST'])
def addComment():
    # 获取 POST 请求的 JSON 数据
    data = request.get_json()
    # 获取具体字段
    userId = data['userId']
    content = data['content']

    # 注册添加数据
    suggestData = suggest(
        content=content,
        user_id=userId,
        create_time=datetime.datetime.now()
        )
    # 通过session进行commit提交修改
    suggestDb.session.add(suggestData)  # 先添加
    suggestDb.session.commit()  # 后提交

    return Result.success("添加成功")


@suggest_blueprint.route('/list', methods=['GET'])
def getCommentByPlantId():
    suggestList = suggest.query.filter().all()
    for suggests in suggestList:
        suggests.create_time = suggests.create_time.strftime('%Y-%m-%d %H:%M:%S')
        user = User.query.filter(User.id == suggests.user_id).first()
        suggests.user_id = user.nick_name
    jsonData = to_json_all(suggestList)
    return Result.success(jsonData)